package com.aorise.utils.push;

import com.aorise.exception.GeTuiException;
import com.gexin.rp.sdk.base.IPushResult;
import com.gexin.rp.sdk.base.ITemplate;
import com.gexin.rp.sdk.base.impl.AppMessage;
import com.gexin.rp.sdk.base.impl.ListMessage;
import com.gexin.rp.sdk.base.impl.SingleMessage;
import com.gexin.rp.sdk.base.impl.Target;
import com.gexin.rp.sdk.base.payload.APNPayload;
import com.gexin.rp.sdk.base.uitls.AppConditions;
import com.gexin.rp.sdk.exceptions.RequestException;
import com.gexin.rp.sdk.http.IGtPush;
import com.gexin.rp.sdk.template.NotificationTemplate;
import com.gexin.rp.sdk.template.TransmissionTemplate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: zhouhao
 * @Date: 2019/6/18
 * @Description: 消息推送模板配置类
 */
@Slf4j
public class AppMessagePush {

    /**
     * 透传模板消息发送
     * @param msg
     */
    public static void sendMessage(PushMessage msg, String appId, String appKey,
                                   String masterSecret, String host) {
        if (msg.getType().equals("android")) {
            ITemplate notificationTemplate = notificationTemplateDemo(msg.getTitle(),
                    msg.getMessageInfo(), msg.getBadge(), msg.getCustomMsg(), appId, appKey);
            pushSingleMessage(msg, notificationTemplate, true, appId, appKey, masterSecret, host);
//            ITemplate iosTransmissionTemplate = iosTransmissionTemplate(msg.getTitle(),
//                msg.getMessageInfo(), msg.getBadge(), msg.getCustomMsg(), appId, appKey);// 带APNPayload
//            pushSingleMessage(msg, iosTransmissionTemplate, false, appId, appKey, masterSecret,
//                host);
            log.info("android : 消息推送 --->"+msg.toString() );
        } else if (msg.getType().equals("ios")) {
            /** ios透传模板配置 */
            ITemplate iosTransmissionTemplate = iosTransmissionTemplate(msg.getTitle(),
                msg.getMessageInfo(), msg.getBadge(), msg.getCustomMsg(), appId, appKey);// 带APNPayload

            /** ios个推 */
            pushSingleMessage(msg, iosTransmissionTemplate, true, appId, appKey, masterSecret,
                host);
            log.info("ios : 消息推送 --->"+msg.toString() );
        }
    }

    /**
     * 透传模板消息发送（app）
     * @param msg
     */
    public static void sendAPPMessage(PushMessage msg, String appId, String appKey,
                                      String masterSecret, String host) {
        if (msg.getType().equals("ios")) {
            /** ios透传模板配置 */
            ITemplate iosTransmissionTemplate = iosTransmissionTemplate(msg.getTitle(),
                    msg.getMessageInfo(), msg.getBadge(), msg.getCustomMsg(),appId, appKey);// 带APNPayload

            /** ios群推 */
            pushAppMessage(msg, iosTransmissionTemplate, true, appId,appKey, masterSecret,
                    host);
        }
    }

    /**
     * 单个推送
     * @param msg
     * @param template 推送模板
     * @param offline
     */
    private static void pushSingleMessage(PushMessage msg, ITemplate template, boolean offline,
                                          String appId, String appKey, String masterSecret,
                                          String host) {
        IGtPush push = new IGtPush(host, appKey, masterSecret);

        SingleMessage message = new SingleMessage();

        message.setOffline(offline);
        // 离线有效时间，单位为毫秒，可选
        message.setOfflineExpireTime(24 * 3600 * 1000);
        message.setData(template);
        // 可选，1为wifi，0为不限制网络环境。根据手机处于的网络情况，决定是否下发
        message.setPushNetWorkType(0);
        Target target = new Target();
        target.setAppId(appId);

        if (StringUtils.isNotBlank(msg.getCid())) {
            target.setClientId(msg.getCid());
        }
        if (StringUtils.isNotBlank(msg.getAlias())) {
            target.setAlias(msg.getAlias());
        }

        IPushResult ret = null;

        try {
            ret = push.pushMessageToSingle(message, target);
        } catch (RequestException e) {
            e.printStackTrace();
            ret = push.pushMessageToSingle(message, target, e.getRequestId());
        }

        if (ret != null) {
            System.out.println(ret.getResponse().toString());
        } else {
            throw new GeTuiException("个推服务器响应异常");
        }
    }

    /**
     * 应用群推送
     * @param template 推送模板
     * @param offline
     */
    public static void pushAppMessage(PushMessage msg, ITemplate template, boolean offline, String appId, String appKey, String masterSecret,
                                      String host) {
        IGtPush push = new IGtPush(host, appKey, masterSecret);

        AppMessage message = new AppMessage();
        message.setData(template);
        message.setOffline(offline);
        // 离线有效时间，单位为毫秒，可选
        message.setOfflineExpireTime(24 * 3600 * 1000);
        // 可选，1为wifi，0为不限制网络环境。根据手机处于的网络情况，决定是否下发
        message.setPushNetWorkType(0);
        //推送给App的目标用户需要满足的条件
        AppConditions cdt = new AppConditions();
        //appId
        List<String> appIdList = new ArrayList<String>();
        appIdList.add(appId);

        cdt.addCondition(AppConditions.TAG,msg.getTagList());
        message.setConditions(cdt);
        message.setAppIdList(appIdList);
        IPushResult ret = push.pushMessageToApp(message);

        if (ret != null) {
            System.out.println(ret.getResponse().toString());
        } else {
            throw new GeTuiException("群推服务器响应异常");
        }
    }

    /**
     * 群推(对指定列表用户推送消息)
     * @param msg
     * @param template
     * @param offline
     */
    private static void pushGroupMessage(PushMessage msg, ITemplate template, boolean offline,
                                         List<String> aliasList, String appId, String appKey,
                                         String masterSecret, String host) {
        IGtPush push = new IGtPush(host, appKey, masterSecret);
        ListMessage message = new ListMessage();
        message.setData(template);
        // 设置消息离线，并设置离线时间
        message.setOffline(true);
        // 离线有效时间，单位为毫秒，可选
        message.setOfflineExpireTime(24 * 1000 * 3600);
        // 配置推送目标
        List<Target> targets = new ArrayList<Target>();
        for (String alias : aliasList) {
            Target target = new Target();
            target.setAppId(appId);
            target.setAlias(alias);
            targets.add(target);
        }
        // taskId用于在推送时去查找对应的message
        String taskId = push.getContentId(message);
        IPushResult ret = push.pushMessageToList(taskId, targets);
        if (ret != null) {
            System.out.println(ret.getResponse().toString());
        } else {
            throw new GeTuiException("群推服务器响应异常");
        }
    }



    /**
     * ios透传，设置APNPayload参数
     * @param title
     * @param messageInfo
     * @param badge
     * @return
     */
    private static TransmissionTemplate iosTransmissionTemplate(String title, String messageInfo,
                                                                String badge, String customMsg,
                                                                String appId, String appKey) {
        /** 透传消息模板创建 */
        TransmissionTemplate template = transmissionTemplate(messageInfo, appId, appKey);

        /** Ios透传APNs通知参数配置 */
        APNPayload payload = getApnPayload(title, messageInfo, badge, customMsg);

        /** Ios透传模板设置APNs */
        template.setAPNInfo(payload);

        return template;
    }

    /** Ios透传APNs通知参数配置
     * @param title
     * @param messageInfo
     * @param badge
     * @return
     */
    private static APNPayload getApnPayload(String title, String messageInfo, String badge,
                                            String customMsg) {
        APNPayload payload = new APNPayload();
        // +1在已有数字基础上加1显示，设置为-1时，在已有数字上减1显示，设置为数字时，显示指定数字
        payload.setAutoBadge(badge);
        payload.setContentAvailable(1);
        //        payload.setSound("123.wav");
        payload.setSound("default");
        payload.setCategory("$由客户端定义");
        payload.addCustomMsg("customMsg", customMsg); //返回给前端页面跳转数据信息
        // //简单模式APNPayload.SimpleMsg
        payload.setAlertMsg(new APNPayload.SimpleAlertMsg(messageInfo));

        //字典模式使用APNPayload.DictionaryAlertMsg
        //payload.setAlertMsg(getDictionaryAlertMsg());

        return payload;
    }

    /**
     * 透传消息模板
     * @param messageInfo
     * @return
     */
    private static TransmissionTemplate transmissionTemplate(String messageInfo, String appId,
                                                             String appKey) {
        TransmissionTemplate template = new TransmissionTemplate();
        template.setAppId(appId);
        template.setAppkey(appKey);
        //透传模板内容设置
        template.setTransmissionContent(messageInfo);
        // 透传消息设置，1为强制启动应用，客户端接收到消息后就会立即启动应用；2为等待应用启动
        template.setTransmissionType(2);
        return template;
    }

    /**
     * 字典模式使用APNPayload.DictionaryAlertMsg
     * @return
     */
    private static APNPayload.DictionaryAlertMsg getDictionaryAlertMsg() {
        APNPayload.DictionaryAlertMsg alertMsg = new APNPayload.DictionaryAlertMsg();
        alertMsg.setBody("body");
        alertMsg.setActionLocKey("ActionLockey");
        alertMsg.setLocKey("LocKey");
        alertMsg.addLocArg("loc-args");
        alertMsg.setLaunchImage("launch-image");
        // iOS8.2以上版本支持
        alertMsg.setTitle("Title");
        alertMsg.setTitleLocKey("TitleLocKey");
        alertMsg.addTitleLocArg("TitleLocArg");
        return alertMsg;
    }

    /**
     * 点击通知打开应用模板 Android
     * @param title
     * @param messageInfo
     * @param badge
     * @return
     */
    private static NotificationTemplate notificationTemplateDemo(String title, String messageInfo,
                                                                 String badge, String customMsg,
                                                                 String appId, String appKey) {
        NotificationTemplate template = new NotificationTemplate();
        // 设置APPID与APPKEY
        template.setAppId(appId);
        template.setAppkey(appKey);
        // 设置通知栏标题与内容
        template.setTitle(title);
        template.setText(messageInfo);
        // 配置通知栏图标
        template.setLogo("icon.png");
        // 配置通知栏网络图标
        template.setLogoUrl("");
        // 设置通知是否响铃，震动，或者可清除
        template.setIsRing(true);
        template.setIsVibrate(true);
        template.setIsClearable(true);
        template.setAPNInfo(getApnPayload(title, messageInfo, badge, customMsg));
        template.setTransmissionType(1);
        template.setTransmissionContent("notification." + messageInfo);
        return template;
    }
}
